﻿using System.Text.RegularExpressions;

namespace 监听读取日志文件变动;

public static class LogFile
{
    // 记录读取到的最后一条数据
    public static string lastData = string.Empty;

    public static void watcher_Changed(object sender, FileSystemEventArgs e)
    {
        (sender as FileSystemWatcher).EnableRaisingEvents = false;

        // 确保changed事件可以被重新触发。
        (sender as FileSystemWatcher).EnableRaisingEvents = true;

        // 判断是否更新数据
        System.Threading.Tasks.Task.Factory.StartNew(() =>
        {
            // 新增的日志文本信息
            List<string> list = new List<string>();

            // 使用正则，筛选日志文件
            string strReg = @"\.log\b";

            if (Regex.IsMatch(e.Name, strReg))
            {
                lock (lastData)
                {
                    FileStream fs = File.Open(@"D:\ACCT\log\" + e.Name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    // 流读取器
                    StreamReader sr = new StreamReader(fs);
                    try
                    {
                        // 第一次读取，更新lastData
                        if (lastData == string.Empty)
                        {
                            string s = string.Empty;
                            while (!sr.EndOfStream)
                            {
                                s = sr.ReadLine();
                                lastData = s;
                            }
                            list.Add(s);
                        }
                        // 新增日志数据
                        else
                        {
                            string s = string.Empty;
                            do
                            {
                                s = sr.ReadLine();
                            } while (s != lastData);
                            while (!sr.EndOfStream)
                            {
                                s = sr.ReadLine();
                                list.Add(s);
                            }
                        }

                        // 文件在线浏览可以做的事
                        foreach (var str in list)
                        {
                            lastData = str;
                            //DoWork(lastData)
                        }
                    }
                    catch (Exception ex)
                    {
                        //。。。处理错误
                    }
                    finally
                    {
                        sr.Close();
                        fs.Close();
                    }
                }
            }
        });
    }
}